package org.stvd.controller.admin;

import java.util.List;
import java.util.Map;

import javax.validation.Valid;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.validation.BindingResult;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.stvd.common.Consts;
import org.stvd.common.aspectj.lang.annotation.Log;
import org.stvd.common.aspectj.lang.enums.BusinessType;
import org.stvd.common.utils.InterfaceResult;
import org.stvd.controller.BaseController;
import org.stvd.core.util.StringUtil;
import org.stvd.entities.admin.Guids;
import org.stvd.service.admin.GuidsService;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import springfox.documentation.annotations.ApiIgnore;

/**
 * 系统平台-控制类
 * @author houzx
 */
@Api(tags="系统平台接口类")
@Controller
@RequestMapping("/admin/guids")
public class GuidsController extends BaseController{

    @Autowired
    private GuidsService guidsService;
    
    @Value("${top_guid}")
    private String topGuid = "";
    
    private String tmpURL = "/admin/guids/";
    
    /**
     * 平台GUID管理请求
     * @param guids
     * @return
     */
    @ApiIgnore
    @RequestMapping(value="management")
    public String onPageLoad(@ModelAttribute("guids") Guids guids){
        if(!StringUtil.isEmpty(topGuid)) {
            // 指定加载某个平台下的所有平台信息
            Guids queryGuid = guidsService.findByPk(Guids.class, topGuid);
            if(queryGuid!=null) {
                guids.setInnerCode(queryGuid.getInnerCode());
            }
        }
        List<Guids> guidsList = guidsService.listAllGuids(guids.getInnerCode(), guids.getStatus());
        map.put("guidsList", guidsList);
        return tmpURL + "GuidsManagement.html";
    }
    
    /**
     * 平台GUID新增
     * @param guids
     * @return
     */
    @ApiIgnore
    @GetMapping(value="add")
    public String onAddLoad(@ModelAttribute("guids") Guids guids){
        map.put("guidsList", guidsService.listAllGuids("", "T"));
        return tmpURL + "GuidsAdd.html";
    }
    
    @ApiOperation("新增平台信息")
    @Log(title = "新增平台信息", businessType = BusinessType.INSERT)
    @PostMapping(value="add")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onAddAction(
        @Valid @ModelAttribute("guids") Guids guids, BindingResult bindingResult){
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        result.transferResult(guidsService.insertGuidsAndInit(guids));
        map.clear();
        return result;
    }
    
    /**
     * 平台信息修改
     * @param gid
     * @return
     */
    @ApiIgnore
    @GetMapping(value="edit/{gid}")
    public String onEditLoad(@PathVariable String gid){
        Guids guids = guidsService.findByPk(Guids.class, gid);
        if(guids != null){
            map.put("guids", guids);
            map.put("guidsList", guidsService.listAllGuids("", "T"));
        }
        return tmpURL +"GuidsEdit.html";
    }
    
    @ApiOperation("修改平台信息")
    @Log(title = "修改平台信息", businessType = BusinessType.UPDATE)
    @PostMapping(value="edit")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onEditActive(
        @Valid @ModelAttribute("guids") Guids guids, BindingResult bindingResult){
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        if (bindingResult.hasErrors()) {
            result.setError(bindingResult.getAllErrors().get(0).getDefaultMessage());
            return result;
        }
        if(guids.getUpperGuid().equals(guids.getGuid()) 
            || guidsService.isChildGuids(guids.getGuid(), guids.getUpperGuid())){
            result.setError("上级平台不能是当前平台或下属平台！");
            return result;
        }
        String originInnerCode = guids.getInnerCode();
        String newInnerCode = guidsService.getInnerCode(guids.getUpperGuid());
        //更新子菜单的innerCode
        List<Guids> guidsChildList = guidsService.listAllChildGuids(guids.getGuid());
        for (Guids guidsChild : guidsChildList) {
            if (!guidsChild.getGuid().equals(guids.getGuid())) {
                guidsChild.setInnerCode(guidsChild.getInnerCode().replace(originInnerCode, newInnerCode));
                guidsService.update(guidsChild);
            }
        }
        guids.setInnerCode(newInnerCode);
        guidsService.update(guids);
        
        map.clear();
        result.setMsg("修改成功！");
        return result;
    }
    
    /**
     * GUID删除
     * @param guid
     * @param title
     * @return
     */
    @ApiOperation("删除平台信息")
    @Log(title = "删除平台信息", businessType = BusinessType.DELETE)
    @PostMapping(value="del")
    @ResponseBody
    public InterfaceResult<Map<String, Object>> onProDelete(String guid,String title) {
        InterfaceResult<Map<String, Object>> result = new InterfaceResult<Map<String,Object>>();
        List<Guids> list = guidsService.listGuidsByUpperGuid(guid);
        if(list!=null && list.size() > 0) {
            result.setError("删除‘"+title+"’失败！失败原因：当前平台存在子平台！");
        }else {
           guidsService.delete(Guids.class,guid);
           result.setMsg("删除‘"+title+"’成功！");
        }
        return result ;
    }
    
    /**
     * 异步获取所有平台列表信息
     * @return
     */
    @ApiOperation("获取平台列表信息")
    @PostMapping(value = "queryAll")
    @ResponseBody
    public List<Guids> onQueryAll() {
        return guidsService.listAllChildGuids(StringUtil.isEmpty(topGuid) ? Consts.GUID : topGuid);
    }
}
